<template>
  <view class="container-wrap" :style="{ height: currentHeight }">
    <view class="title">
      <view @click="isFullScreenFn">接卸效率</view>
      <view class="flex">
        <view style="width: 150px">
          <uni-select
            v-model="selectValue"
            dataKey="coalSourceType"
            dataValue="id"
            :clear="false"
            :localdata="selectList"
            @change="conditionChange"
          ></uni-select>
        </view>
        <view style="width: 60px; margin-left: 10px">
          <uni-select
            v-model="dateType"
            dataKey="name"
            dataValue="value"
            :clear="false"
            :localdata="dateTypeList"
            @change="conditionChange"
          ></uni-select>
        </view>
      </view>
    </view>
    <view class="echart-wrap">
      <echarts-uniapp
        ref="efficiencyWaveRef"
        canvasId="efficiencyWaveChart"
        @touchStart="touchStart"
        @touchEnd="touchEnd"
      ></echarts-uniapp>
    </view>
    <uni-loading v-show="showLoading"></uni-loading>
  </view>
</template>
<script>
import { colorList } from './baseData.js';
import { unloadEfficiency, getScreenCondition } from '@/api/dashboard';
import { getCurrentDateForParam } from '@/utils/common.js';
import uniLoading from '../common/uni-loading/uni-loading.vue';
import echartsUniapp from '../common/echarts-uniapp/echarts-uniapp';
export default {
  components: {
    echartsUniapp,
    uniLoading
  },
  props: {
    currentHeight: {
      type: String,
      default: '100vh'
    }
  },
  data() {
    return {
      showLoading: false,
      canSlide: 0,
      touchXStart: 0,
      slideDirection: 0,
      xAxisList: [],
      selectValue: '',
      selectList: [],
      dateType: 'daterange',
      dateTypeList: [
        { name: '日', value: 'daterange' },
        { name: '周', value: 'week' },
        { name: '月', value: 'month' },
        { name: '季', value: 'quarter' },
        { name: '年', value: 'year' }
      ],
      cacheRankList: [],
      option: {
        color: colorList,
        tooltip: {
          trigger: 'axis',
          responsive: true,
          confine: true,
          axisPointer: {
            type: 'line',
            axis: 'auto',
            snap: true
          },
          textStyle: {
            testShadowColor: 'transparent',
            textShadowBlur: 10
          },
          padding: 5
        },
        legend: {
          top: 6,
          data: []
        },
        grid: {
          left: 0,
          right: '2%',
          top: 40,
          bottom: 0,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisTick: {
            show: false
          },
          data: []
        },
        yAxis: {
          min: 0,
          type: 'value',
          minInterval: 1,
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLine: {
            show: true
          },
          axisLabel: {
            formatter: '{value}分'
          }
        },
        series: []
      }
    };
  },
  async mounted() {
    await this.getScreenConditionFn();
    this.unloadEfficiencyFn();
  },
  methods: {
    isFullScreenFn() {
      if (this.currentHeight === '100vh') {
        return;
      }
      this.$tab.navigateTo('/packageA/pages/dashboard/efficiencyWave');
    },
    touchStart(e) {
      this.touchXStart = e.changedTouches[0].clientX || 0;
    },
    touchEnd(e) {
      const touchXEnd = e.changedTouches[0].clientX;
      if (this.touchXStart - touchXEnd > 0) {
        this.slideDirection = 1;
        this.unloadEfficiencyFn();
      }
      if (this.touchXStart - touchXEnd < 0) {
        if (this.canSlide !== 0) {
          return;
        }
        this.slideDirection = 0;
        this.unloadEfficiencyFn();
      }
    },
    conditionChange() {
      this.xAxisList = [];
      this.unloadEfficiencyFn();
    },
    async getScreenConditionFn() {
      const res = await getScreenCondition({ flag: false });
      if (res.code === 0) {
        const result = res.data || [];
        this.selectList = result.map((e) => {
          e.id = `${e.productId}${e.supplierId}${e.coalSourceId}${e.purchaserId}`;
          return e;
        });
        this.selectValue = this.selectList[0].id;
      }
    },
    async unloadEfficiencyFn() {
      let dateTime = '';
      if (!this.xAxisList.length) {
        dateTime = getCurrentDateForParam(new Date());
      }
      if (this.xAxisList.length) {
        if (!this.slideDirection) {
          dateTime = this.xAxisList[0]?.value?.split('_')?.[0];
        }
        if (this.slideDirection) {
          dateTime =
            this.xAxisList[this.xAxisList.length - 1]?.value?.split('_')?.[1];
        }
      }
      const data = {
        timePeriod: this.dateType,
        coalSourceId: this.getTransportData()?.coalSourceId,
        coalSourceName: this.getTransportData()?.coalSourceName,
        productId: this.getTransportData()?.productId,
        productName: this.getTransportData()?.productName,
        purchaserId: this.getTransportData()?.purchaserId,
        purchaserName: this.getTransportData()?.purchaserName,
        reqSource: 1,
        slideDirection: this.slideDirection,
        dateTime: dateTime
      };
      this.showLoading = true;
      const res = await unloadEfficiency(data);
      if (res.code === 0) {
        this.canSlide = res?.data?.canSlide;
        this.option.tooltip.formatter = this.getTooltip();
        this.cacheRankList = res?.data?.dataInfoList || [];
        const dataInfoList = res?.data?.dataInfoList || [];
        this.option.yAxis.max = this.isHasData(dataInfoList) ? 1 : null;
        this.xAxisList = res?.data?.dateRespVOList || [];
        this.option.legend.data = this.getLegendData(dataInfoList);
        this.option.xAxis.data = this.xAxisList.map((e) => e.label) || [];
        this.option.series = this.getSeriesList(dataInfoList);
        this.$refs.efficiencyWaveRef.initChart(this.option);
      }
      this.showLoading = false;
    },
    isHasData(list) {
      return list
        .filter((e) => e.durationType !== '平均趟数')
        .every((m) => !m.screenVisRankInfoRespVOS?.length);
    },
    getTransportData() {
      return this.selectList.find((e) => e.id === this.selectValue);
    },
    getLegendData(list) {
      return list
        .filter((e) => e.durationType !== '平均趟数')
        .map((m) => m.durationType);
    },
    getSeriesList(list) {
      return list
        .filter((e) => e.durationType !== '平均趟数')
        .map((e) => {
          return {
            name: e.durationType,
            type: 'line',
            data: this.getSeriesData(e.screenVisRankInfoRespVOS || [])
          };
        });
    },
    getSeriesData(list) {
      return list.map((e) => e.duration);
    },
    getTooltip() {
      return (param) => {
        if (param.length === 1) {
          const value = param[0];
          const data = this.cacheRankList.find(
            (e) => e.durationType === value?.seriesName
          );
          const rankList = data.screenVisRankInfoRespVOS || [];
          const ascRankList =
            rankList[value.dataIndex]?.screenVisRankInfoVoAsc || [];
          const descRankList =
            rankList[value.dataIndex]?.screenVisRankInfoVoDesc || [];
          let result = `${value?.name}\n\r`;
          if (!ascRankList.length && !descRankList.length) {
            result += '暂无数据';
          } else if (ascRankList.length && descRankList.length) {
            result += `${value?.seriesName} ${value.value || 0}${
              value?.seriesName === '平均趟数' ? '趟' : '分'
            }\n\r`;
            result += '前三名：\n\r';
            ascRankList.forEach((e, v) => {
              result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                e.duration || 0
              }分\n\r`;
            });
            result += '后三名：\n\r';
            descRankList.forEach((e, v) => {
              if (v === descRankList.length - 1) {
                result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                  e.duration || 0
                }分`;
              } else {
                result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                  e.duration || 0
                }分\n\r`;
              }
            });
          } else {
            result += `${value?.seriesName} ${value.value || 0}${
              value?.seriesName === '平均趟数' ? '趟' : '分'
            }\n\r`;
            if (ascRankList.length) {
              result += '前三名：\n\r';
              ascRankList.forEach((e, v) => {
                if (v === ascRankList.length - 1) {
                  result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                    e.duration || 0
                  }分`;
                } else {
                  result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                    e.duration || 0
                  }分}\n\r`;
                }
              });
            }
            if (descRankList.length) {
              result += '后三名：\n\r';
              descRankList.forEach((e, v) => {
                if (v === descRankList.length - 1) {
                  result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                    e.duration || 0
                  }分`;
                } else {
                  result += `${e.vehicleNo} ${e.driverName} ${e.driverPhone} ${
                    e.duration || 0
                  }分\n\r`;
                }
              });
            }
          }
          return result;
        } else {
          let result = `${param[0]?.name}\n\r`;
          param.forEach((e, v) => {
            if (v === param.length - 1) {
              result += `${e.marker} ${e.seriesName} ${e.value}分`;
            } else {
              result += `${e.marker} ${e.seriesName} ${e.value}分\n\r`;
            }
          });
          return result;
        }
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.container-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px 10px;
  background-color: #ffffff;
  border-radius: 8px;
  .title {
    display: flex;
    font-size: 14px;
    color: #000000;
    font-weight: 600;
    padding-bottom: 11px;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e6e6e6;
  }
  .echart-wrap {
    flex: 1;
  }
  .flex {
    display: flex;
  }
  .flex-direction {
    flex-direction: column;
  }
}
</style>
